package main

import (
	"fmt"
	"net/http"
	// "os"
	// "2018_Go/1/lissajous"
	// "image"
	// "image/color"
	// "image/gif"
	// "io"
	"log"
	// "math"
	// "math/rand"
	// "os"
	"sync"
	// "time"
)

var mu sync.Mutex
var count int

func main() {
	http.HandleFunc("/", handler)
	http.HandleFunc("/count", counter)
	http.HandleFunc("/f1", handler1)
	http.HandleFunc("/f2", handler2)
	http.HandleFunc("/f2", func(w http.ResponseWriter, r *http.Request) { lissajous(w) })
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	count++
	mu.Unlock()
	fmt.Fprintf(w, "url.path = %q\n", r.URL.Path)
}

func counter(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	fmt.Fprintf(w, "Count %d\n", count)
	mu.Unlock()
}

func handler1(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)
	for k, v := range r.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}
	fmt.Fprintf(w, "Host = %q\n", r.Host)
	fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)
	if err := r.ParseForm(); err != nil {
		log.Print(err)
	}
	for k, v := range r.Form {
		fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
	}
}

// func lissajous(out io.Writer) {
// 	const (
// 		cycles  = 5     // number of complete x oscillator revolutions
// 		res     = 0.001 // angular resolution
// 		size    = 100   // image canvas covers [-size..+size]
// 		nframes = 64    // number of animation frames
// 		delay   = 8     // delay between frames in 10ms units
// 	)

// 	freq := rand.Float64() * 3.0 // relative frequency of y oscillator
// 	anim := gif.GIF{
// 		LoopCount: nframes,
// 	}
// 	phase := 0.0 // phase difference
// 	// 外层循环64次
// 	for i := 0; i < nframes; i++ {
// 		rect := image.Rect(0, 0, 2*size+1, 2*size+1)
// 		// 每次外层循环生成一个单独的动态帧，大小201*201,像素都是palette(白色)
// 		img := image.NewPaletted(rect, palette)
// 		// 内层循环
// 		for t := 0.0; t < cycles*2*math.Pi; t += res {
// 			x := math.Sin(t)
// 			y := math.Sin(t*freq + phase)
// 			img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5),
// 				blackIndex)
// 		}
// 		phase += 0.1
// 		anim.Delay = append(anim.Delay, delay)
// 		anim.Image = append(anim.Image, img)
// 	}
// 	gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
// }
